import { StyleSheet, Text, View, FlatList, Image, Pressable } from 'react-native';
import React, { useState, useCallback } from 'react';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { ContentStatus, DialogModal } from '~/components';
import { px2dp, scale } from '~/utils/px2dp';
import { getUserArticleListApi, writeCourse } from '~/api/deviceApi';
import { formatTimestamp } from '~/utils/formatDate';
import { appStore, observer } from '~/store';

type Type = 'remote' | 'normal';
interface Props {
    type: Type;
    subDevice_sn: string;
    pupillus_mobile: string;
}

export default observer((props: Props) => {
    const { t } = useTranslation();
    const { type, subDevice_sn, pupillus_mobile } = props;
    const navigation: any = useNavigation();
    const [listData, setListData] = useState([]);
    const [isRefreshing, setIsRefreshing] = useState(false); // 是否刷新
    const [visible, setVisible] = useState(false);
    const [selectInfo, setSelectInfo] = useState<any>({});
    const sourceMap = {
        0: t('CourseList.t6'),
        1: t('CourseList.t7'),
        2: t('CourseList.t8'),
        3: t('CourseList.t9'),
        4: t('CourseList.t8'),
        5: t('CourseList.t10'),
        6: t('CourseList.t11'),
        7: t('CourseList.t12'),
    };
    const getData = () => {
        getUserArticleListApi({ mobile: pupillus_mobile }).then((res) => {
            setIsRefreshing(false);
            setListData(res.data);
        });
    };
    const handleRefresh = () => {
        getData();
        setIsRefreshing(true);
    };
    const myCourseDetailes = (res) => {
        const courseImg = res.base_course_img;
        navigation.navigate('CourseDetailes', {
            base_course_img: courseImg,
        });
    };
    const openModal = (res) => {
        setSelectInfo(res);
        setVisible(true);
    };
    const onConfirm = () => {
        writeCourse({ device_sn: subDevice_sn, mobile: pupillus_mobile || '', id: selectInfo.id }).then((res) => {
            if (res.status == 1) {
                Toast.show({ content: t('CourseList.t13') });
                getData();
            } else {
                Toast.show({ content: t('CourseList.t14') });
            }
            setVisible(false);
        });
    };
    const renderItem = ({ item }) => {
        return (
            <View style={[styles.list_item]}>
                <View style={styles.row}>
                    <Image
                        style={styles.course_image}
                        source={{ uri: item.course_img ? item.course_img : '/images/course_img.png' }}
                    />
                    <View style={styles.info}>
                        <View style={styles.row}>
                            <Text style={styles.course_name}>
                                {appStore.app.language == 'zh'
                                    ? item.course_goods_name
                                    : item.en_name
                                    ? item.en_name
                                    : item.course_goods_name}
                            </Text>
                            <View style={styles.tag}>
                                <Text style={styles.tagText}>
                                    {item.course_days}
                                    {t('CourseList.t1')}
                                </Text>
                            </View>
                        </View>
                        <Text style={styles.creat_time}>
                            {formatTimestamp(item.add_time, 1)} {sourceMap[item.source] || item.source}
                        </Text>
                    </View>
                </View>
                <View style={styles.line} />
                <View style={[styles.row, styles.around]}>
                    <Pressable onPress={() => myCourseDetailes(item)}>
                        <Text style={styles.course_detailes}>{t('CourseList.t2')}</Text>
                    </Pressable>
                    {/* <Divider
                        bg="emerald.500"
                        thickness="1"
                        backgroundColor={'#eee'}
                        height={4}
                        mx="2"
                        orientation="vertical"
                    /> */}
                    <Pressable onPress={() => openModal(item)}>
                        <Text style={styles.activeCourse}>{t('CourseList.t3')}</Text>
                    </Pressable>
                </View>
            </View>
        );
    };
    useFocusEffect(
        useCallback(() => {
            getData();
        }, []),
    );
    return (
        <View style={styles.container}>
            <FlatList
                contentContainerStyle={styles.contentContainerStyle}
                showsVerticalScrollIndicator={false}
                data={listData}
                renderItem={renderItem}
                keyExtractor={(item, index) => index.toString()}
                onEndReachedThreshold={0.1}
                onRefresh={handleRefresh}
                refreshing={isRefreshing}
                ListEmptyComponent={() => <ContentStatus status="empty" source={{ title: t('CourseList.t4') }} />}
            />
            <DialogModal
                visible={visible}
                onCancel={() => setVisible(false)}
                content={t('CourseList.t5')}
                onConfirm={onConfirm}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    around: {
        justifyContent: 'space-around',
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
        marginHorizontal: px2dp(32),
    },
    list_item: {
        backgroundColor: '#fff',
        marginTop: px2dp(24),
        padding: px2dp(24),
        borderRadius: px2dp(20),
    },
    course_image: {
        width: px2dp(60),
        height: px2dp(60),
    },
    info: {
        marginLeft: px2dp(24),
    },
    course_name: {
        fontWeight: 'bold',
        fontSize: scale(28),
        color: '#191919',
        width: '80%',
        lineHeight: px2dp(40),
    },
    tag: {
        backgroundColor: '#1877FF',
        justifyContent: 'center',
        alignItems: 'center',
        width: px2dp(80),
        height: px2dp(40),
        borderRadius: px2dp(12),
        marginLeft: px2dp(12),
    },
    tagText: {
        color: '#fff',
        fontSize: scale(22),
    },
    creat_time: {
        color: '#a4a4a4',
        fontSize: scale(22),
        marginTop: px2dp(12),
    },
    line: {
        width: '100%',
        height: px2dp(2),
        backgroundColor: '#eee',
        marginVertical: px2dp(32),
    },
    course_detailes: {
        color: '#a4a4a4',
        fontWeight: 'bold',
    },
    activeCourse: {
        color: '#1877FF',
        fontWeight: 'bold',
    },
});
